package com.project.school_flate.serviceimpl.shop;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.project.school_flate.dto.shop.ShopCommodityDto;
import com.project.school_flate.entity.shop.ShopCommodity;
import com.project.school_flate.entity.shop.ShopInfo;
import com.project.school_flate.entity.shop.table.ShopCommodityTableDef;
import com.project.school_flate.entity.shop.table.ShopInfoTableDef;
import com.project.school_flate.entity.table.shop.ShopCommodityTable;
import com.project.school_flate.entity.table.shop.ShopInfoTable;
import com.project.school_flate.mapper.shop.ShopCommodityMapper;
import com.project.school_flate.mapper.shop.ShopInfoMapper;
import com.project.school_flate.service.shop.ShopCommodityService;
import com.project.school_flate.util.PoToDTO;
import com.project.school_flate.util.Result.Result;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;

/**
 *  服务层实现。
 *
 * @author 马维健
 * @since 2024/1/2
 */
@Service
public class ShopCommodityServiceImpl extends ServiceImpl<ShopCommodityMapper, ShopCommodity> implements ShopCommodityService {

    @Autowired
    private ShopCommodityMapper oShopCommodityMapper;

    @Autowired
    private ShopInfoMapper oShopInfoMapper;

    /**
     * 获取商品
     * @param oShopCommodityDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getShopCommodity(ShopCommodityDto oShopCommodityDto) throws Exception {
        List<ShopCommodity> oShopCommodityList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        //判断是否传入店铺ID
        if(StringUtils.isNotBlank(oShopCommodityDto.getShopId())){
            queryWrapper.where(ShopCommodityTable.SHOP_COMMODITY.SHOP_ID.eq(oShopCommodityDto.getShopId()));
        }
        //判断是否传入商品类型
        if(StringUtils.isNotBlank(oShopCommodityDto.getCommodityTypeId())){
            queryWrapper.where(ShopCommodityTable.SHOP_COMMODITY.COMMODITY_TYPE_ID.eq(oShopCommodityDto.getCommodityTypeId()));
        }
        //判断是否传入商品状态
        if(oShopCommodityDto.getState() != null){
            queryWrapper.where(ShopCommodityTable.SHOP_COMMODITY.STATE.eq(oShopCommodityDto.getState()));
        }
        //判断是否传入商品ID
        if(StringUtils.isNotBlank(oShopCommodityDto.getId())){
            queryWrapper.where(ShopCommodityTable.SHOP_COMMODITY.ID.eq(oShopCommodityDto.getId()));
        }
        queryWrapper.orderBy("create_time desc");
        //是否分页
        if(oShopCommodityDto.getPage() != null && oShopCommodityDto.getLimit() != null){
            Page<ShopCommodity> ShopCommodityPage = oShopCommodityMapper.paginateWithRelations(oShopCommodityDto.getPage(),oShopCommodityDto.getLimit(),queryWrapper);
            oShopCommodityList = ShopCommodityPage.getRecords();
            total = ShopCommodityPage.getTotalRow();
        }else{
            oShopCommodityList = oShopCommodityMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oShopCommodityList.size();
        }
        //PoToDto
        List<ShopCommodityDto> oShopCommodityDtoList = (List<ShopCommodityDto>) PoToDTO.poToDtoList(oShopCommodityList,new ShopCommodityDto());
        return Result.ok(oShopCommodityDtoList,total);
    }

    /**
     * 添加商品
     * @param oShopCommodityDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result addShopCommodity(ShopCommodityDto oShopCommodityDto) throws Exception {
        ShopCommodity oShopCommodity = oShopCommodityDto;
        //判断是否参与储蓄折扣
        if(oShopCommodity.getIsInSave() == 0){
            oShopCommodity.setMemberPrice(oShopCommodity.getOriginalPrice());
            oShopCommodity.setSaveDiscountRatio(1.0);
        }else{
            if(oShopCommodity.getMemberPrice() == null){
                return Result.error("请填写会员价");
            }
            if(oShopCommodity.getMemberPrice().compareTo(oShopCommodity.getOriginalPrice()) >= 0){
                return Result.error("会员价不能大于等于原价");
            }
            oShopCommodity.setSaveDiscountRatio(oShopCommodity.getMemberPrice() / oShopCommodity.getOriginalPrice());
        }
        if(oShopCommodityMapper.insert(oShopCommodity) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("添加商品失败");
        }
        return Result.ok(oShopCommodity);
    }

    /**
     * 修改商品
     * @param oShopCommodityDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result updateShopCommodity(ShopCommodityDto oShopCommodityDto) throws Exception {
        ShopCommodity oShopCommodity = oShopCommodityDto;
        if(oShopCommodityMapper.update(oShopCommodity) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("修改商品失败");
        }
        return Result.ok("修改商品成功");
    }

    /**
     * 删除商品
     * @param oShopCommodityDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result deleteShopCommodity(ShopCommodityDto oShopCommodityDto) throws Exception {
        ShopCommodity oShopCommodity = oShopCommodityDto;
        if(oShopCommodityMapper.deleteById(oShopCommodity.getId()) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("删除商品失败");
        }
        return Result.ok("删除商品成功");
    }

    /**
     * 获取商品（客户）
     * @param oShopCommodityDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getShopCommodityUser(ShopCommodityDto oShopCommodityDto) throws Exception {
        List<ShopCommodity> oShopCommodityList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        //判断是否传入店铺ID
        queryWrapper.where(ShopCommodityTable.SHOP_COMMODITY.SHOP_ID.eq(oShopCommodityDto.getShopId()));
        queryWrapper.where(ShopCommodityTable.SHOP_COMMODITY.STATE.in(0,2));
        //判断是否传入商品类型
        if(StringUtils.isNotBlank(oShopCommodityDto.getCommodityTypeId())){
            queryWrapper.where(ShopCommodityTable.SHOP_COMMODITY.COMMODITY_TYPE_ID.eq(oShopCommodityDto.getCommodityTypeId()));
        }
        //判断是否传入商品ID
        if(StringUtils.isNotBlank(oShopCommodityDto.getId())){
            queryWrapper.where(ShopCommodityTable.SHOP_COMMODITY.ID.eq(oShopCommodityDto.getId()));
        }
        //判断是否传入商品状态
        if(oShopCommodityDto.getState() != null){
            queryWrapper.where(ShopCommodityTable.SHOP_COMMODITY.STATE.eq(oShopCommodityDto.getState()));
        }
        queryWrapper.orderBy("no asc");
        //是否分页
        if(oShopCommodityDto.getPage() != null && oShopCommodityDto.getLimit() != null){
            Page<ShopCommodity> ShopCommodityPage = oShopCommodityMapper.paginateWithRelations(oShopCommodityDto.getPage(),oShopCommodityDto.getLimit(),queryWrapper);
            oShopCommodityList = ShopCommodityPage.getRecords();
            total = ShopCommodityPage.getTotalRow();
        }else{
            oShopCommodityList = oShopCommodityMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oShopCommodityList.size();
        }
        //PoToDto
        List<ShopCommodityDto> oShopCommodityDtoList = (List<ShopCommodityDto>) PoToDTO.poToDtoList(oShopCommodityList,new ShopCommodityDto());
        return Result.ok(oShopCommodityDtoList,total);
    }

    /**
     * 获取推荐商品（客户）
     * @param oShopCommodityDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getRecommendShopCommodityUser(ShopCommodityDto oShopCommodityDto) throws Exception {
        QueryWrapper queryWrapper = new QueryWrapper();
        //判断是否传入校园ID
        if(StringUtils.isNotBlank(oShopCommodityDto.getSchoolId())){
            //获取校园下的店铺
            QueryWrapper qWShopInfo = new QueryWrapper();
            qWShopInfo.where(ShopInfoTableDef.SHOP_INFO.SCHOOL_ID.eq(oShopCommodityDto.getSchoolId()));
            List<ShopInfo> oShopInfoList = oShopInfoMapper.selectListByQuery(qWShopInfo);
            if(CollectionUtils.isEmpty(oShopInfoList)){
                return Result.ok(new ArrayList(),0);
            }
            //获取查到的店铺ID集合
            List<String> oShopInfoIdList = new ArrayList<>();
            oShopInfoList.forEach(item->{oShopInfoIdList.add(item.getId());});
            queryWrapper.where(ShopCommodityTableDef.SHOP_COMMODITY.SHOP_ID.in(oShopInfoIdList));
        }
        queryWrapper.where(ShopCommodityTableDef.SHOP_COMMODITY.IS_SYSTEM_RECOMMEND.eq(1));
        queryWrapper.where(ShopCommodityTableDef.SHOP_COMMODITY.STATE.eq(0));
        List<ShopCommodity> oShopCommodityList = oShopCommodityMapper.selectListWithRelationsByQuery(queryWrapper);
        return Result.ok(oShopCommodityList,oShopCommodityList.size());
    }

}
